<template>
    <div class="common-layout">
       <el-container>
           <el-header class="header_activate"> 
              <div><h3>我录入的所有试题</h3></div>            
               <div class="search_activate" id="top_position"> 
                   <el-input v-model="state.input_keyword" placeholder="输入关键词" />
                   <el-button type="warning" :icon="Search" @click="searchQuestionContentClick"></el-button> 
               </div>
               <div class="filter">
                   <el-dropdown @command="handleCommand">
                       <span class="el-dropdown-link">
                           时间筛选
                       <el-icon class="el-icon--right">
                           <arrow-down />
                       </el-icon>
                       </span>
                       <template #dropdown>
                       <el-dropdown-menu>                        
                           <el-dropdown-item command="7">近7天</el-dropdown-item>
                           <el-dropdown-item command="15">近15天</el-dropdown-item>
                           <el-dropdown-item command="30" divided>近30天</el-dropdown-item>
                           <el-dropdown-item command="90" disabled>近90天</el-dropdown-item>
                           <el-dropdown-item command="180" >近半年</el-dropdown-item>
                           <el-dropdown-item command="0">无限制</el-dropdown-item>
                       </el-dropdown-menu>
                       </template>
                   </el-dropdown>
               </div>
           </el-header>
           <el-divider />
           <el-main>
              <div><h3>只有当试题设置为上线和公有，才能被浏览</h3></div>
               <el-table class="tableClass" :data="state.questionList" stripe                   
                   :header-cell-style="{ background: '#eef1f6', color: '#606266' }"                    
                    border
               > 
                   <el-table-column type="index" width="45" label="序" />                 
                   <el-table-column width="250" property="content" label="内容" show-overflow-tooltip />           
                    <el-table-column width="80" property="open_level" label="公开"/>
                    <el-table-column width="80" property="online" label="上/下线"/>
                   <el-table-column width="115" property="publish_time" label="录入日期"/>
                   <el-table-column width="90" label="审核状态">
                       <template #default="scope">
                            <el-text v-if="scope.row.application_info">{{ scope.row.application_info.status_cn }}</el-text>
                    </template> 
                    </el-table-column>
                   <el-table-column align="center" width="110" label="操作" > 
                       <template #default="scope">
                          <div class="operate">
                              <el-tooltip class="box-item" effect="dark" content="设为公开" placement="top" v-if="scope.row.open_level==='private'">                         
                                  <el-icon style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'public')">
                                      <Unlock />
                                  </el-icon>
                              </el-tooltip>
                              <el-tooltip class="box-item" effect="light" content="设为私藏" placement="top" v-else>
                                  <Lock style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'private')" />
                              </el-tooltip>
                              <el-tooltip class="box-item" effect="light" content="申请上线" placement="top" v-if="scope.row.online===false"> 
                                  <Top style="width: 1em; height: 1em;margin-right: 8px" @click="onlineClick(scope.row.id)" />
                              </el-tooltip>
                              <el-tooltip class="box-item" effect="dark" content="修改试题" placement="top"> 
                                  <Edit style="width: 1em; height: 1em;" @click="updateQuestionClick(scope.row,scope.row.id)" />
                              </el-tooltip>
                          </div>
                       </template>
                   </el-table-column>
               </el-table>
               
               <el-pagination
               background
               layout="total, pre, pager, next"
               :total="state.total"                
               :page-size="state.pageSize"            
               @current-change="handleCurrentChange"
               />
           </el-main>
           <EditeOneQuestionDialoge ref="editeOneQuestionDialogeRef" :type="state.type" :fileList="state.fileList" :question="state.question" :father_method="reGetQuestion"></EditeOneQuestionDialoge>
       </el-container>
   </div>
  </template>
  <script setup>
  
  import { Search, Unlock, Lock, Top, Document, ArrowDown, Edit } from '@element-plus/icons-vue'
  import {onMounted, reactive, ref } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from '@/utils/axios'
  import EditeOneQuestionDialoge from '@/views/EditeOneQuestionDialoge.vue'
  
  const editeOneQuestionDialogeRef = ref(null)
  const state = reactive({
    fileList:[],
    type:'update',
    input_keyword: '',
    days: 0,
    total: 0, // 总条数
    currentPage: 1, // 当前页
    pageSize: 10, // 分页大小
    lastGetDataMethod: 'default',
    question:Object,
    updateQuestion_id:Number,
    questionList:[],
  })
  const getQuestionsByDefault=()=>{
      let params = {
          days: state.days,
          page: state.currentPage,
          size: state.size,
      }
      state.lastGetDataMethod = 'default'
      axios.get(`/questions/question_owner_all/`, {params}).then(res => {
          if (res.code==200){
              console.log("获取试题成功：", res)
              state.questionList = res.data.results
              state.total = res.total
          }else{       
              console.log("error", res.message)
          }
      })
      .catch((error)=>{
          console.log("获取录入试卷失败", error)
      })
  }
  const getQuestionsBySearch=()=>{
      let params = { 
        query_key: state.input_keyword,
        page: state.currentPage,
        size: state.size,
      }
      state.lastGetDataMethod = 'search'
      axios.get(`/questions/search_with_owner_all/`, {params}).then(res => {
          if (res.code==200){
              console.log("搜索结果：", res)
              state.questionList = res.data.results
              state.total = res.total
          }else{
              ElMessage.error("没有查询到记录")
              console.log("error", res.message)
          }
      })
      .catch((error)=>{
          console.log("获取数据错误：", error)
      })
  }
  // 页面初始化
  onMounted(() => {
    getQuestionsByDefault()
  })
  //设置天数
  const handleCommand=(days=0)=>{
    days = parseInt(days)
    state.days = days
    reGetQuestion()
  }
  // 设置试题公开或私密
  const SetPublicOrPrivateClick=(id, open_level)=>{  
      let params = {
      pk: id,
      type: 0,
      open_level: open_level,
      days: state.days,
      }
      axios.patch(`/questions/${params.pk}/setup_open_level/`, params).then(res => {
          if (res.code==200){
              // console.log("申请列表：", res)
              ElMessage.success("试卷公开程度操作成功，返回首页！")
              state.questionList = res.data.results
              reGetQuestion()             
          }else if(res.code==1021){
              ElMessage.error("试题id错误！")
          }
          else if(res.code==1022){
              ElMessage.error("此操作没有必要！")
              console.log("error", res)
          }else{
              ElMessage.error("此操作失败！")
          }
      })
      .catch((error)=>{
          console.log("获取数据错误：", error)
      })
  }
  
  // 滚到顶端
  const scrollToTop=()=>{
   document.querySelector('#top_position').scrollIntoView(true);
  }
  //根据上次的获取方式，重新获取题目列表
  const reGetQuestion=()=>{
     if (state.lastGetDataMethod == 'default'){
        getQuestionsByDefault()
      }else{
        getQuestionsBySearch()
      }
  }
  //点击页码时触发
  const handleCurrentChange = (newPage)=>{
      state.currentPage = newPage
      reGetQuestion()
      scrollToTop()
  }
 
  const searchQuestionContentClick=()=>{    
      console.log("要搜索试题啦")
      getQuestionsBySearch()
  }
  //点击更新试卷按钮，并从试卷列表中，获取该试卷的数据，开启抽屉，
  const updateQuestionClick=(obj,id)=>{
      state.updateQuestion_id=id
      state.question=obj
      editeOneQuestionDialogeRef.value.open(state.updateQuestion_id,obj)
  }
  // 申请试题上线
  const onlineClick=(id)=>{
    let params={ id:id }
    axios.post(`/QuestionOnlineApplicationModelViewSet/`, params).then(res => {
          if (res.code==200){
              // console.log("申请列表：", res)
              ElMessage.success("上线申请成功，请耐心等待管理员审核！")
            //   state.questionList = res.data.results
            //   reGetQuestion()
          }else if(res.code==1024){
          ElMessage.error("你的申请已被管理员拒绝，请修改内容，并联系管理员！")
              console.log("error", res)
          }else if(res.code==1022){
              ElMessage.error("你的申请已经提交，请耐心等待管理员审核！")
              console.log("error", res)
          }else{
            console.log("操作失败", res)
            ElMessage.error("此操作失败！")
          }
      })
      .catch((error)=>{
          console.log("获取数据错误：", error)
      })
  }
  
  </script>
  
  <style scoped>
  .search_activate {
   display: flex;
   flex-flow: row nowrap;
   /* justify-content: space-between; */
   align-items: center;
   margin: 0 auto;
   height: 30px;
  }
  .header_activate{
   display: flex;
   flex-flow: row nowrap;
   justify-content:flex-start;
   align-items: center;
   padding: 0px;
   height: 30px;
   width:800px;
  }
  span{
   font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
   font-size: medium;
  }
  .tableClass .cell{   
   padding: 0!important;
   height: 20px!important;
   line-height: 20px!important;
   text-align: center;
   font-size: 10px;
  }
  .filter{
      background-color: rgb(219, 226, 221);
  }
  .operate{
      display: flex;
      flex-flow: row nowrap;
      justify-content:space-between;
      align-items: center;
      padding: 2px;   
  }
  </style>